package chapter01;

import java.util.Arrays;

public class ThreeSumClosest {
    //排序 双指针 去重
    //Max_Value-(-1)==Max_Value
    public int threeSumClosest(int[] nums, int target) {
        int length=nums.length;
        int closestSum=nums[0]+nums[1]+nums[2],item;
        Arrays.sort(nums);
        for(int i=0;i<length-2;i++){
            if(i>0&&nums[i-1]==nums[i]){
                continue;
            }
            int pre=i+1;
            int next=length-1;
            while(pre<next){
                item=nums[i]+nums[pre]+nums[next];
                if(Math.abs(item-target)<Math.abs(closestSum-target)){
                    closestSum=item;
                }
                if(item-target>0){
                    while(pre<next&&nums[next-1]==nums[next]){
                        next--;
                    }
                    next--;
                }else if(item-target<0){
                    while (pre<next&&nums[pre+1]==nums[pre]){
                        pre++;
                    }
                    pre++;
                }else {
                    return closestSum;
                }
            }
        }
        return closestSum;
    }

//    public static void main(String[] args) {
//        System.out.println(new chapter01.ThreeSumClosest().threeSumClosest(new int[]{1,1,-1,-1,3},-1));
//    }
}


